package top.goldenyear.porpoise.system.auth.service;

import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.solon.annotation.Db;
import java.time.LocalDateTime;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import top.goldenyear.porpoise.framework.web.core.model.PageResult;
import top.goldenyear.porpoise.framework.web.core.model.query.QPage;
import top.goldenyear.porpoise.framework.web.core.service.BaseService;
import top.goldenyear.porpoise.system.auth.model.Session;
import top.goldenyear.porpoise.system.auth.model.proxy.SessionProxy;

/**
 * 登录会话表 Service 服务层
 *
 * @author airhead
 * @since 2024-10-12
 */
@Component
@Slf4j
public class SessionService extends BaseService<Session, SessionProxy> {
  @Db private EasyEntityQuery easyEntityQuery;

  public SessionService() {
    super(Session.class, SessionProxy.class);
  }

  public Boolean createSession(Session session) {
    return save(session);
  }

  public Boolean updateSession(Session session) {
    return updateById(session);
  }

  public Session getSession(String id) {
    return getById(id);
  }

  public Boolean deleteSession(String id) {
    return deleteById(id);
  }

  public List<Session> listSession(Session session) {
    return list(session);
  }

  public PageResult<Session> paginateSession(QPage qPage, Session session) {
    return paginate(qPage.getPageNumber(), qPage.getPageSize(), session);
  }

  public void storeToken(Integer accountId, String type, long timeToLiveSeconds, String token) {
    Session session = getById(token);
    if (session != null) {
      return;
    }

    // expires 用于设置 session 的过期时间点
    LocalDateTime expires = LocalDateTime.now().plusSeconds(timeToLiveSeconds);
    // 保存登录 session 到数据库
    session = new Session();
    session.setId(token);
    session.setAccountId(accountId);
    session.setCreateTime(LocalDateTime.now());
    session.setExpires(expires);
    session.setType(type);
    save(session, false);
  }

  @Override
  protected EasyEntityQuery easyEntityQuery() {
    return easyEntityQuery;
  }
}
